<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dataForm.id ? '编辑分组' : '新增分组'"
    :width="dailogWidth"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="dataForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      v-loading="loading"
    >
      <el-form-item label="分组名称" prop="name" label-position="right">
        <el-input style="width: 90%" v-model="dataForm.name" placeholder="请输入分组名称" :disabled="!!dataForm.id" :clearable="true"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark" label-position="right">
        <el-input style="width: 90%" v-model="dataForm.remark" placeholder="请输入备注" :clearable="true"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" v-loading="loading">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addGroupApi } from '@/api/equipmentManagement/massTexting.api'
import { formatParams } from "@/utils";
import useToggle from "@/hooks/useToggle";
import useDailogWidth from "@/hooks/useDailogWidth";
const dailogWidth = useDailogWidth("90%", "35%")
const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();
const emit = defineEmits(["refresh"]);
const dataForm = ref({
  name: "",
  remark: "",
  app: "WA",
  bundle: "net.whatsapp.WhatsApp",
})
const rules = {
  name: [{ required: true, message: '请输入分组名称', trigger: 'blur' },]
}
const handleClose = () => {
  setDialogVisible(false)
}

let inform = null
const handleOpen = (params) => {
  setDialogVisible(true)

  nextTick(() => {
    resetForm()
    if(typeof params === 'function') {
      inform = params
    }
    else if(params) {
      dataForm.value.id = params.id || void undefined
      dataForm.value.name = params.name
      dataForm.value.remark = params.remark
      dataForm.value.app = params.app
      dataForm.value.bundle = params.bundle
    }
  })
}

const formRef = ref(null)
const submitForm = async () => {
  setLoading(true)
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      addGroupApi({
        ...dataForm.value
      }).then(res => {
        emit("refresh");
        inform && inform(res)
        setLoading(false)
        handleClose()
      }).finally(() => {
        setLoading(false)
        handleClose()
      })
    }
  })
}

const resetForm = () => {
  if (!formRef.value) return
  dataForm.value.id = void undefined
  formRef.value.resetFields()
}

defineExpose({
  handleOpen,
})
</script>
